package me.yricky.mayu.utils.fasta

import me.yricky.mayu.ui.fasta.FastaSeqModel
import me.yricky.mayu.utils.asList
import java.io.File

/**
 * @author Yricky
 * @date 2022/3/25
 */
object Fasta {
    fun readFile(f: File):Iterator<FastaSeqModel>{
        return object :Iterator<FastaSeqModel>{
            val fr = f.bufferedReader()
            private val seqSb = StringBuilder()
            var nextSeqName:String? = readNextName()

            fun readNextName():String?{
                seqSb.clear()
                var line:String?
                while (let{line = fr.readLine();line != null}){
                    if(line?.startsWith('>') == true){
                        return line?.substring(1)
                    } else{
                        seqSb.append(line)
                    }
                }
                return null
            }

            override fun hasNext(): Boolean = nextSeqName != null

            override fun next(): FastaSeqModel {
                val name =  "$nextSeqName"
                nextSeqName = readNextName()
                return FastaSeqModel().also {
                    it.name = name
                    it.seq.addAll(seqSb.toString().asList())
                }
            }

        }
    }

    fun openFile(f:File):Iterable<FastaSeqModel>{
        return object :Iterable<FastaSeqModel>{
            override fun iterator(): Iterator<FastaSeqModel> = readFile(f)
        }
    }
}